package com.liwei.vip.mall.goods.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liwei.vip.mall.goods.mapper.AdItemsMapper;
import com.liwei.vip.mall.goods.mapper.SkuMapper;
import com.liwei.vip.mall.goods.model.AdItems;
import com.liwei.vip.mall.goods.model.Sku;
import com.liwei.vip.mall.goods.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
//将商品信息展示到页面中
@CacheConfig(cacheNames = "ad-items-skus")
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    @Autowired
    private AdItemsMapper adItemsMapper;

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 根据推广产品分类ID查询指定分类下的产品列表
     *
     * @param id
     * @return
     */
    //cacheNames就是当前缓存的一级命名空间  唯一的key起名用spring支持的SpEL表达式 获取当前获取id的值
    @Cacheable(key = "#id")//第二次就没有走数据库了
    @Override
    public List<Sku> typeSkuItems(Integer id) {
        System.out.println("查询数据库.....");
        //1.查询当前分类下的所有列表信息
        QueryWrapper<AdItems> adItemsQueryWrapper = new QueryWrapper<>();
        adItemsQueryWrapper.eq("type", id);
        List<AdItems> adItems = adItemsMapper.selectList(adItemsQueryWrapper);

        if(adItems.size()>0 && adItems!=null){
            //2.根据推广列表查询产品列表信息
            List<String> skuids=adItems.stream()
                    .map(adItem->adItem.getSkuId())
                    .collect(Collectors.toList());
            return skuMapper.selectBatchIds(skuids);
        }
        return null;
    }

    /**
     * 根据分类id删除指定推广的数据
     * @param id
     * @return
     */
    @CacheEvict(key = "#id")
    @Override
    public void deltypeSkuItems(Integer id) {}

    /**
     * 根据分类id修改指定推广数据
     *
     * @param id
     */
    @CachePut(key = "#id")
    @Override
    public List<Sku> updatetypeSkuItems(Integer id) {
        //1.查询当前分类下的所有列表信息
        QueryWrapper<AdItems> skuQueryWrapper = new QueryWrapper<>();
        skuQueryWrapper.eq("type", id);
        List<AdItems> adItems = adItemsMapper.selectList(skuQueryWrapper);
        //2.根据推广列表查询产品列表信息
        List<String> skuids = adItems.stream()
                .map(adItem -> adItem.getSkuId())
                .collect(Collectors.toList());
        return skuids==null || skuids.size()<=0 ? null:skuMapper.selectBatchIds(skuids);
    }
}
